<template>
	<m-layout title="购物车" :goBack="false" :gap="cartList.length > 0 ? '24' : '0'">
		<template v-if="cartList.length !== 0" slot="right">
			<text style="font-size: 30rpx;" :style="'color:' + (isEditor ? '#FA2B47' : '#333333')"
				@click="isEditor = !isEditor">{{ isEditor ? '退出编辑' : '编辑' }}</text>
		</template>
		<template v-if="cartList.length !== 0">
			<!-- 主列表 -->
			<view class="cart_box">
				<view v-for="(item, index) in cartList" :key="index">
					<m-block gap="36 32 36 0" spa=" 0 0 16" class="li">
						<view class="flex-between">
							<m-icon size="40" spa="25" :color="item.checked ? '#FA2B47' : '#C5C5C5'"
								:type.sync="item.checked ? 'icon-chenggong' : 'icon-weixuanzhongyuanquan'"
								@click="check(item)"></m-icon>
							<view class="right">
								<!-- <view class="shop_box flex"
									@click="Jump('/pages/home/goodsShop/goodsShop?shopID=' + item.sellerUserID)">
									<view class="shop_img"><m-image :size="40" types="shop" :src="item.picurl" /></view>
									<view>{{ item.sellerUserName || '平台商家' }}</view>
								</view> -->
								<view class="goods_box flex" style="    align-items: initial;"
									@click="Jump('/pages/home/goodsDetail/goodsDetail?id=' + item.gid)">
									<view class="goods_img">
										<m-image size="126" radius="20" :src="item.picurl.split(',')[0]" />
									</view>
									<view class="goods_content flex-column jc-space-between">
										<view class="goods_title">
											<text class="otp2">{{ item.goodsname }}</text>
										</view>
										<text class="fs21 text-grey">所选：{{item.attrname?item.attrname:'默认规格'}}</text>
										<view class="flex">
											<m-price :size="[32,24]" :value="item.price" color="#FA2B47" />
											<view class="ml-8" v-if="item.price3">
												<text class="fs21 ml-4" style="color:#666">代理价</text>
												<m-price :size="[26,24]" :value="item.price3" color="#666" />
											</view>
										</view>
									</view>
								</view>
								<view class="goods_price flex-between jc-flex-end">
									<view class="">
										<m-price class="mr-32" :size="[38,24]" :value="item.isdls?item.price3:item.price"
											color="#FA2B47"></m-price>
									</view>
									<uni-number-box class="step" :disabled="disabled" :min="1" v-model="item.buycount"
										:index="index" @change=" e => { addCard(e, item)} ">
									</uni-number-box>
								</view>
							</view>
						</view>
					</m-block>
				</view>
			</view>
			<!-- <m-loading gap="100 0" :list='cartList' :index="pageIndex" :total="totalPage" :loading="isLoading" /> -->


			<!-- 结算操作 -->
			<template v-if="!isEditor&&allCheck.length>0">
				<view class="bottom_all flex-between">
					<view class="flex ai-center">
						<view class="fs25 flex mr-12">
							已选<text class="text-primary fs28">{{ totalPrice[0] }}</text>件</view>
						<view class="flex fs26">
							<text class="mr-8">合计</text>
							<view class="flex">
								<m-price :size="[34, 24]" :value="totalPrice[1]"
									color="#F95F5F"></m-price>
							</view>
						</view>
					</view>
					<view class="">
						<m-button class="small plr-48 ptb-16" size="small" type="primary" @click="submit">结算</m-button>
					</view>
				</view>
			</template>
			<!-- 编辑操作 -->
			<template v-if="isEditor">
				<view class="bottom_all flex-between">
					<view class="flex-center">
						<m-icon size="42" spa="0 16 0 0"
							:color="allCheck.length == cartList.length ? '#FA2B47' : '#C5C5C5'"
							:type.sync="allCheck.length == cartList.length ? 'icon-chenggong' : 'icon-weixuanzhongyuanquan'"
							@click="checkAll"></m-icon>
						<view class="fs28">全选</view>
					</view>
					<view v-if="isEditor" class="flex-center">
						<m-button style="border-color:#f4bf40 " @click="isShow = true"
							class="small resetBtn">清空</m-button>
						<m-button @click="deleteGoods" class="small" style="margin-left: 20rpx">删除</m-button>
					</view>
				</view>
			</template>
		</template>
		<!-- 缺省页 -->
		<template v-if="cartList.length== 0 && !isLoading">
			<view>
				<m-block bgColor="unset" class="emptyCart" radius="0">
					<view class="top flex-column flex-center">
						<m-empty title="暂无数据" size="300" gap="38 0 60 0" icon="card-empty"></m-empty>
						<!-- <m-button type="hollow" class="emptyBt"
							@click="Jump({url:'/pages/classfy/classfy',mode:4})">去逛逛</m-button> -->
					</view>
				</m-block>
			</view>
		</template>
		<!-- 删除弹窗 -->
		<m-dialog :isShow="isShow" :showCancel="true" cancelText="取消" confirmText="删除全部" @handleCancel="isShow = false"
			@handleConfirm="clearGoods">
			<view class="pop_txt">确定删除全部吗？</view>
		</m-dialog>
	</m-layout>
</template>

<script>
	import { mapState } from 'vuex';
	import { GetShopCar, ShopCar_Del, ShopCar_Edit, GoodsFirst } from '@/api/Goods.js';
	export default {
		data() {
			return {
				isShow: false,
				cartNo: '', // 购物车编号
				allChecked: false, //全选状态  true|false
				isEditor: false,
				isLoading: false,
				disabled: false,
				pageIndex: 1,
				pageSize: 50
			};
		},
		onLoad() {
			this.$store.commit('goods/CLEAR');
			this.init();
			this.isEditor = false;
		},
		computed: {
			...mapState({
				nowId: state => state.address.nowId,
				cartList: state => state.goods.cartList
			}),
			//全选
			allCheck() {
				const a = this.cartList.filter(item => {
					return item.checked == true;
				});
				return a;
			},
			//计算总价  和 总量
			totalPrice() {
				let amount = 0,
					tPrice = 0;
				this.cartList.forEach(item => {
					if (item.checked) {
						tPrice += (item.isdls?item.price3:item.price) * item.buycount;
						amount += item.buycount;
					}
				});
				return [amount, tPrice];
			}
		},
		watch: {
			//监听编辑  切换时全为 false
			isEditor(val) {
				this.cartList.forEach(item => {
					item.checked = false;
				});
			}
		},
		methods: {
			init() {
				this.GetUsersCart();
			},
			checkAll() {
				const a = this.allCheck.length == this.cartList.length;
				//先获取状态  再给全选赋值
				this.cartList.forEach(item => {
					item.checked = !a;
				});
				this.cartList = JSON.parse(JSON.stringify(this.cartList));
			},
			///////////////////////////////////// 事件监听 ////////////////////////////////////////
			///////////////////////////////////// 点击事件 ////////////////////////////////////////
			//选中状态处理
			check(item) {
				// if (!this.isEditor) {
				// 	this.cartList.forEach((items) => {
				// 		items.checked = false;
				// 	})
				// }
				item.checked = !item.checked;
				this.cartList = JSON.parse(JSON.stringify(this.cartList));
			},
			// 购物车修改数量
			async addCard(e, item) {
				console.log('item===>', item)
				let data = {
					carid: item.id,
					count: e,
				};
				this.disabled = true;
				const res = await ShopCar_Edit(data);
				this.disabled = false;
				// this.Toast(res.msg)
				if (!res.success) {
					item.count = item.count - 1;
				}
			},
			// 商品详情
			async GoodsFirst(id) {
				const { data, success } = await GoodsFirst({
					id: id
				});
				return Promise.resolve(data)
			},
			// 结算
			async submit() {
				// let idx = this.cartList.find(item => {
				// 	return item.checked
				// });
				// const info = await this.GoodsFirst(idArr)
				// // 是否有有属性
				// const attrData = idx.attrid ? {
				// 	attrId: idx.attrid,
				// 	price: idx.price,
				// 	attrPrice: idx.price,
				// 	attrName: info.attr.filter(item => {
				// 		return item.id == idx.attrid
				// 	})[0]['goodsname']
				// } : { attrId: 0 };

				// const goods = {
				// 	...info,
				// 	buycount: idx.buycount,
				// 	...attrData
				// };

				const goods = this.allCheck;
				this.$store.commit('goods/SET_PAYGOODS', goods);
				this.Jump('/pages/order/sureOrder/sureOrder');
			},
			// 获取购物车列表
			async GetUsersCart() {
				this.isLoading = true;
				const { success, list } = await GetShopCar({
					pageIndex: this.pageIndex,
					pageSize: this.pageSize,
				});
				this.$store.commit('goods/SET_CARTLIST',list);
				console.log('this.cartList', this.cartList)
				this.isLoading = false;
				// this.cartList = list;
			},
	
			// 批量删除购物车商品
			async deleteGoods() {
				let a = [];
				this.allCheck.forEach(item => {
					a.push(item.id.toString());
				});
				let { success, data } = await ShopCar_Del(a);
				if (success) {
					this.init();
				}
			},
			// 清空购物车
			async clearGoods() {
				let a = this.cartList.map(item => {
					return item.id.toString()
				}, [])

				let { success, data } = await ShopCar_Del(a);
				if (success) {
					this.isShow = false;
					this.init();
				}
			}
		},
		// onReachBottom() {
		// 	console.log('触底了');
		// 	this.$refs.hot.getData();
		// },
		onTabItemTap(e) {
			// tab 点击时执行，此处直接接收单击事件
			if (this.tabClick) {
				uni.pageScrollTo({
						scrollTop: 0
					},
					50
				);
			}
			this.tabClick = true;
			setTimeout(() => {
				this.tabClick = false; // 200ms 内没有第二次点击，就当作单击
			}, 200);
		}
	};
</script>

<style lang="scss" scoped>
	.cart_box {
		position: relative;
		padding-bottom: calc(50% - var(--window-bottom));
		// .cart_list {bottom:;
		// 	::v-deep .uni-checkbox-input {
		// 		border-radius: 100%;
		// 	}

		// 	::v-deep .uni-checkbox-input:hover {
		// 		border-radius: 100%;
		// 		border-color: unset;
		// 	}
		// }
		.li {
			.right {
				overflow: hidden;
				flex: 1;
			}
		}

		.shop_box {
			font-size: 30rpx;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: bold;
			color: #333333;

			.shop_img {
				width: 40rpx;
				height: 40rpx;
				margin-right: 16rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}
		}

		.goods_box {
			align-items: flex-start;

			.goods_img {}

			.goods_content {
				flex: 1;
				margin-left: 20rpx;
				overflow: hidden;
				// padding-right: 40rpx;

				.goods_title {
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #333333;
				}

				.goods_spu {
					max-width: 100%;
					display: inline-flex;
					overflow: hidden;
					box-sizing: border-box;

					background: #f6f6f6;
					border-radius: 50rpx;
					padding: 2rpx 18rpx;
					margin: 8rpx 0 15rpx 0;

					text {
						display: inline-block;
						max-width: 100%;

						font-size: 24rpx;
						font-family: PingFang SC-Regular, PingFang SC;
						font-weight: 400;
						color: #999999;
					}
				}

				.goods_label {
					.label_v {
						display: inline-block;
						font-size: 20rpx;
						font-family: PingFang SC-Regular, PingFang SC;
						font-weight: 400;
						color: #fa2b47;
						border: 1px solid #fa2b47;
						border-radius: 4rpx;
						padding: 4rpx 6rpx;
						margin: 12rpx 12rpx 0 0;
					}
				}
			}
		}

		.goods_price {
			padding-top: 20rpx;
		}
	}

	.bottom_all {
		width: 100%;
		box-sizing: border-box;
		position: fixed;
		bottom: var(--window-bottom);
		left: 0;
		padding: 12rpx 24rpx;
		box-sizing: border-box;
		background-color: #fdfdfd;
		border-bottom: 2rpx solid #f8f8f8;

		::v-deep .uni-radio-input:hover {
			border-color: #d1d1d1;
		}
	}

	// 缺省页
	.emptyCart {
		.top {
			background-color: #ffffff;

			.emptyBt {
				margin: 41rpx 0 49rpx 0;
				display: inline-block;
				padding: 17rpx 102rpx;
				// border-color: #fa2b47;
				// color: #fa2b47;
			}
		}

		.goods-list {
			.title {
				text-align: center;
				font-size: 30rpx;
				font-family: PingFang SC;
				font-weight: bold;
				color: #333333;
			}

			.list-box {
				display: grid;
				grid-template-columns: 1fr 1fr;
				grid-row-gap: 16rpx;
				grid-gap: 27rpx;
				padding-top: 20rpx;

				.li:nth-of-type(1n + 2) {}
			}
		}
	}

	.pop_txt {

		font-size: 28rpx;
		font-family: PingFang SC-Regular, PingFang SC;
		font-weight: 400;
		color: #222222;
		text-align: center;
		padding-top: 48rpx;
		margin-bottom: 66rpx;
	}

	.resetBtn {
		background: #f4bf40 !important;
	}
</style>